<template>
  <Dialog
    :title="t('judgeScene.final.candidateSettings')"
    v-model="dialogVisible"
    width="570"
    :fullscreen="false"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-form-item :label="t('scxFinalDebateTime.form.date')">
        {{ settingsInfo ? formatDate(settingsInfo.finalDate, 'YYYY-MM-DD') : '' }}
      </el-form-item>
      <el-form-item :label="t('scxFinalDebateTime.fields.gap')" prop="gap">
        <el-input-number
          style="width: 100%"
          v-model="formData.gap"
          :min="0"
          :placeholder="t('common.inputTextPlaceholder') + t('scxFinalDebateTime.fields.gap')"
        />
      </el-form-item>
      <el-form-item :label="t('scxFinalDebateTime.fields.debateStartTime')" prop="debateStartTime">
        <el-time-picker
          style="width: 100%"
          v-model="startTime"
          :placeholder="
            t('common.selectTextPlaceholder') + t('scxFinalDebateTime.fields.debateStartTime')
          "
          value-format="HH:mm:ss"
        />
      </el-form-item>
      <el-form-item :label="t('scxFinalDebateTime.fields.breakTime')" prop="breakTime">
        <div class="w-1/1 mb-[5px]" v-for="(_, index) in breakTimeArray" :key="index">
          <el-time-picker
            v-model="breakTimeArray[index]"
            is-range
            value-format="HH:mm:ss"
            :start-placeholder="
              t('common.selectTextPlaceholder') + t('scxFinalDebateTime.fields.breakTime')
            "
            :end-placeholder="
              t('common.selectTextPlaceholder') + t('scxFinalDebateTime.fields.breakTime')
            "
          />
          <el-button
            type="danger"
            plain
            size="small"
            :icon="Close as any"
            circle
            class="ml-[10px]"
            :disabled="breakTimeArray.length <= 1"
            @click="handleRemoveBreakTime(index)"
          />
        </div>
        <el-button type="primary" plain @click="breakTimeArray.push([])">
          {{ t('scxFinalDebateTime.form.addBreakTime') }}
        </el-button>
      </el-form-item>
      <el-form-item :label="t('scxFinalDebateTime.fields.priority')" prop="priority">
        <el-radio-group v-model="formData.priority">
          <el-radio value="博士优先">{{ t('scxFinalDebateTime.form.phdFirst') }}</el-radio>
          <el-radio value="硕士优先">{{ t('scxFinalDebateTime.form.masterFirst') }}</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading"
        >{{ t('common.ok') }}
      </el-button>
      <el-button @click="dialogVisible = false">{{ t('common.cancel') }}</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { ScxFinalDebateTimeApi, ScxFinalDebateTimeVO } from '@/api/awards/scxfinaldebatetime'
import { FormRules } from 'element-plus'
import { ScxFinalSettingsApi, ScxFinalSettingsVO } from '@/api/awards/scxfinalsettings'
import { formatDate } from '@/utils/formatTime'
import { Close } from '@element-plus/icons-vue'

/** 师昌绪终评-答辩时间安排 表单 */
defineOptions({ name: 'ScxFinalDebateTimeForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  finalSettingId: undefined,
  breakTime: undefined,
  gap: undefined,
  debateStartTime: undefined,
  priority: undefined,
  remark: undefined
})
const formRules = reactive<FormRules>({
  finalSettingId: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('scxFinalDebateTime.fields.finalSettingId'),
      trigger: 'blur'
    }
  ],
  breakTime: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('scxFinalDebateTime.fields.breakTime'),
      trigger: 'blur'
    }
  ],
  gap: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('scxFinalDebateTime.fields.gap'),
      trigger: 'blur'
    }
  ],
  debateStartTime: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('scxFinalDebateTime.fields.debateStartTime'),
      trigger: 'change'
    }
  ],
  priority: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('scxFinalDebateTime.fields.priority'),
      trigger: 'change'
    }
  ]
})
const formRef = ref() // 表单 Ref

const startTime = computed({
  get: () => {
    return formatDate(formData.value.debateStartTime, 'HH:mm:ss')
  },
  set: (val: string) => {
    let date
    if (settingsInfo.value?.finalDate) {
      date = formatDate(settingsInfo.value.finalDate, 'YYYY-MM-DD')
    } else {
      date = formatDate(new Date(), 'YYYY-MM-DD')
    }
    formData.value.debateStartTime = new Date(date + ' ' + val).getTime() as any
  }
})

const breakTimeArray = ref<string[][]>([[]])

watchEffect(() => {
  formData.value.breakTime = JSON.stringify(breakTimeArray.value) as any
})

const awardsId = ref('')
const settingsInfo = ref<ScxFinalSettingsVO>({} as ScxFinalSettingsVO)
/** 打开弹窗 */
const open = async (_awardsId: string) => {
  awardsId.value = _awardsId
  dialogVisible.value = true
  resetForm()
  formLoading.value = true
  try {
    settingsInfo.value = await ScxFinalSettingsApi.getScxFinalSettingsByAwardsId(awardsId.value)
    const data = await ScxFinalDebateTimeApi.getScxFinalDebateTimeBySettingsId(
      settingsInfo.value.id
    )
    if (data) {
      // 修改
      formType.value = 'update'
      formData.value = data
      breakTimeArray.value = JSON.parse(data.breakTime ?? [[]])
    } else {
      // 新增
      formType.value = 'create'
      formData.value.finalSettingId = settingsInfo.value.id as any
    }
  } finally {
    formLoading.value = false
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ScxFinalDebateTimeVO
    if (formType.value === 'create') {
      await ScxFinalDebateTimeApi.createScxFinalDebateTime(data)
      message.success(t('common.createSuccess'))
    } else {
      await ScxFinalDebateTimeApi.updateScxFinalDebateTime(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    finalSettingId: undefined,
    breakTime: undefined,
    gap: undefined,
    debateStartTime: undefined,
    priority: undefined,
    remark: undefined
  }
  formRef.value?.resetFields()
}

const handleRemoveBreakTime = (index: number) => {
  breakTimeArray.value.splice(index, 1)
}
</script>
